<?php
/*
	[Destoon B2B System] Copyright (c) 2008-2015 www.destoon.com
	This is NOT a freeware, use is subject to license.txt
*/
//@set_time_limit(0);
//define('DT_ADMIN', true);
//define('DT_MEMBER', true);
require 'common.inc.php';
//if($DT_BOT) dhttp(403);
//$_areaids = '';
//$_areaid = array();
//if($DT['city']) {
//    $AREA or $AREA = cache_read('area.php');
//    if($_aid) {
//        $_areaids = $AREA[$_aid]['child'] ? $AREA[$_aid]['arrchildid'] : $_aid;
//        $_areaid = explode(',', $_areaids);
//    }
//} else {
//    $_aid < 1 or dalert('系统未开启分站功能，您的分站管理帐号暂不可用', $MODULE[2]['linkurl'].'logout.php');
//}
//require DT_ROOT.'/admin/global.func.php';
//require DT_ROOT.'/admin/license.func.php';
//require DT_ROOT.'/include/post.func.php';
//require_once DT_ROOT.'/include/cache.func.php';
//isset($file) or $file = 'test';
//$secretkey = 'a'.strtolower(substr(md5(DT_KEY), -6));
//if($CFG['authadmin'] == 'cookie') {
//    $_destoon_admin = get_cookie($secretkey);
//    $_destoon_admin = $_destoon_admin ? intval($_destoon_admin) : 0;
//} else {
//    $session = new dsession();
//    $_destoon_admin = isset($_SESSION[$secretkey]) ? intval($_SESSION[$secretkey]) : 0;
//}
//$_founder = $CFG['founderid'] == $_userid ? $_userid : 0;
//$_catids = $_childs = '';
//$_catid = $_child = array();
//if($file != 'login') {
//
//    if($_groupid != 1 || $_admin < 1  ) msg('', '?file=login&forward='.urlencode($DT_URL));
//
//    if(!admin_check()) {
//        admin_log(1);
//        $db->query("DELETE FROM {$db->pre}admin WHERE userid=$_userid AND url='?".$DT_QST."'");
//        msg('警告！您无权进行此操作 Error(00)');
//    }
//}
//if($DT['admin_log'] && $action != 'import') admin_log();
//if($DT['admin_online']) admin_online();
//if(isset($reason) && is_array($itemid)) admin_notice();
//$widget = isset($widget) ? intval($widget) : 0;
//$psize = isset($psize) ? intval($psize) : 0;
//if($psize > 0 && $psize != $pagesize) {
//    $pagesize = $psize;
//    $offset = ($page-1)*$pagesize;
//}

//if($module == 'destoon') {
//    (include DT_ROOT.'/admin/'.$file.'.inc.php') or msg();
//} else {
//    include DT_ROOT.'/module/'.$module.'/common.inc.php';
//    (include MD_ROOT.'/admin/'.$file.'.inc.php') or msg();


//cache_clear_tag(1);
//$db->expires = $CFG['db_expires'] = $CFG['tag_expires'] = 0;
require DT_ROOT.'/api/weixin/init.inc.php';
$url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid='.$next_openid;
echo "url =>".$url.'<br>';


//遍历获取所有用户信息
$result = $db->query("SELECT * FROM {$DT_PRE}weixin_user where pushstatus=3 or pushstatus=4  ORDER BY itemid ");
$curr_time = time();
sleep(rand(0,10));
if($db->affected_rows($result)) {
    while($user = $db->fetch_array($result)) {
		$pushlist = pushlist($user,$curr_time);         //获取推送的查询列表
		$_openid = $user['openid'];
		$nickname = $user['nickname'];
		$cur_time = time();
		$u_pushtime = $db->get_one("SELECT pushtime FROM {$DT_PRE}weixin_user WHERE openid ='$_openid'");

		echo  '[nickname]'. $user['nickname'].'[openid]'.$_openid.'=><br>';

		$r  =  $db->get_one("SELECT * FROM {$DT_PRE}pushlog where openid = '{$_openid}'  ORDER BY createtime desc limit 1 ");
		$db->query("INSERT INTO {$db->pre}pushlog (openid,nickname,createtime) VALUES ('{$_openid}','{$nickname}','{$cur_time}')");
		if($r){
			if(time() - $r['createtime'] < 60 ){
				continue;
			}
		}

		if(!$pushlist || empty($user['filtercategory']) ){
			echo  '=> nodata to push ......<br>';
		    continue;
		} 
		//10分钟内不再重新发送，解决同时间发送多条重复信息
		if( time() - $u_pushtime['pushtime'] < 600 ){
			echo 'current time no need push msg......<br>';
		    continue;
		} 

    	if($user['pushwx'] || $user['pushemail']){
            $md5 = md5(uniqid());
    		$DT['push_filename']        = 'html_push/push-'.$md5;
            $DT['push_wx_filename']     = 'html_push/push-'.$md5.'-wx';
            $DT['push_email_filename']  = 'html_push/push-'.$md5.'-email';
        	//生成html
        	tohtml('push');
        	$filename = $CFG['com_dir'] ? DT_ROOT.'/'.$DT['push_filename'].'.'.$DT['file_ext'] : DT_CACHE.'/index.inc.html';
        	echo  'filename=>'.$filename.'</br>' ;
        }
        
        $_pushtime = time();
        $db->query("update {$DT_PRE}weixin_user  set pushtime = '$_pushtime' where openid ='$_openid'");

        /*****************************
         *  发送微信
         * *************************/

        if($user['pushwx']){
            echo 'pushwx->user['.$user['nickname'].']===></br>';
            send_wxs($DT['push_wx_filename']);
        }

        /*****************************
         * 发送邮件
         * *************************/

        if($user['pushemail']){
           $emails =  explode(';',$user['email']);
            foreach ($emails as $email){
                echo '<br>pushemail===>'.$email.'</br>';
           	// send_mails();
            // $email = '2839543@qq.com';
            //$title = '您有新的招标信息-合信招标订阅';
			$title=$pushlist[0]['title'];
            $content = file_get_contents($DT['push_email_filename'].'.html');
            $sender = 'admin@china-hxzb.com';
            // echo "send_mail-><br>email->".$email." <br>title->".$title." <br>content->".$content." <br>sender ->".$sender;
            $rs_send_mail = send_mail($email, $title, $content, $sender);
           }
        
    }
        




//defined('test_filename') or define('test_filename', 'test'.time());
//$CFG['test_filename'] or $CFG['test_filename'] = ;

//        msg('首页更新成功 '.(is_file($filename) ? dround(filesize($filename)/1024).'Kb ' : '').'&nbsp;&nbsp;<a href="'.DT_PATH.'" target="_blank">点击查看</a>');
//    sleep(1);
    }
}


function send_wxs($filename) {
	
    global $wx;
    global $access_token;
    global $DT;
    global $MODULE;
    global $user;
    $CAT_TENDER = cache_read('category-23.php');
    //TODO 测试用access_token 覆盖全局access_token
//    $access_token = 'Ng-HUdMaM69drYOBQ6zTLk7FNgKnQlh0xO05eWdBy-BL9_Sws9oF6MOpmzHMNWVhIROfeFjDlVvN8IYlvvSP6Z6m5aSETP6gQrB0wSfTYnMMGYeACAUOG';
//    $openid = 'ow8N8twanbFgcp3xorKmZBkiGf_M'; //TODO 测试用的openid;

    $data = array();
    $data['first'] = array('value'=>"您有新的招标信息！",'color'=>'#173177');
//    $data['title'] = array('value'=>"合信推送",'color'=>'#173177');
//    $data['group'] = array('value'=>"招标信息",'color'=>'#173177');
    $data['Good'] = array('value'=>"合信推送",'color'=>'#173177');
    $data['contentType'] = array('value'=>"招标信息",'color'=>'#173177');

    $str_remark = '';
   $pushtest = pushlist($user);
   $count = 0;
    if (is_array($pushtest)) {
        foreach ($pushtest as $t) {

            $count++;
            //如果标题超过500字则进行截取，补上字符 ...(共X条)
            //经过调试后 350  字截取 440 的不会出现乱码，发送不会丢失【刚刚发布的】信息；
            if(strlen($str_remark) > 300){
                $str_remark = dsubstr($str_remark,250).'
...(共'.count($pushtest).'条)';
				echo "<br>remark===>".$str_remark;
                break;
            }
            $filtertender = explode(",",$t['catid'] );
            if(!empty($filtertender)){
                $arr = array();
                foreach ($filtertender as $v){
                    $cat = $CAT_TENDER[$v];
                    if(!empty($cat)){
                        $arr[] = $cat['catname'];
                    }
                }
                $t['catid'] =implode(',',$arr);
            }

                $str_remark.='
'.$count.' '.  $t['title'].'！['.$t['filtercategory'].']['.$t['filteraddress'].']['.$t['catid'].']';
     }

}
//    http://destoon.haqii.com/mobile/index.php?moduleid=23&itemid=65580
    $to_url = 'http://www.china-hxzb.com/'. $filename.'.'.$DT['file_ext'];
    $str_remark = preg_replace('/\(\d*\)/','',$str_remark);
    //XXX分钟前发布的 根据记录的最近的时间
   // $data['Remark'] = array('value'=>'刚刚发布的：'.$str_remark,'color'=>'#173177');
    $data['remark'] = array('value'=>'刚刚发布的：'.$str_remark,'color'=>'#173177');

    // echo "<br>data['remark']=> ".$data['remark']['value'];
    //TODO修改 模板ID
    // if(empty($openid)){$openid = $user['openid'];}
	$openid = $user['openid'];
    // 1BrT6-eNP_hVpGr1XxE5Vtz6sAReINF-7s-VyMv05YY	  服务状态提醒
    // _65G0HxvZ6_tXFhbm3Hl4bdcyP-y4_vTPU9gcnEv6so    测试号码的匹配模板
    $arr = $wx->send_template($openid, '1BrT6-eNP_hVpGr1XxE5Vtz6sAReINF-7s-VyMv05YY', $data,$access_token,$to_url);
    if($arr['errcode'] == '40001'){
        global $dc ;
        $access_token = $wx->get_token();
        $dc->set('weixin_access_token', $access_token, 7000);
    } 
}
?>
